<?php
/**
 * @title   Article Class File
 * @authors leqing Cao (caoleqing@qq.com)
 * @date    2017-10-25 15:26:06
 * @link 	http://www.cnblogs.com/leqing/
 */
namespace app\api\controller;
class Article extends Common {
	/**
	 * [add_article 新增文章]
	 */
	public function add_article() {
		//1.接受參數
		$data = $this->params;
		//2.存入數據庫
		if (!empty($data['article_content'])) {
			$data['article_content'] = htmlspecialchars($data['article_content']);
		}
		$data['article_ctime'] = time();
		$res = db('article')->insert($data);
		//3.結果返回通知
		if (!$res) {
			$this->return_msg(100001, '文章新增失敗');
		}
		$this->return_msg(200, '文章新增成功', $res);
	}
	/**
	 * [article_list 查询文章列表]
	 * @return [json] [查询结果]
	 */
	public function article_list() {
		# 1.接收参数
		$data = $this->params;
		if (!isset($data['page'])) {
			$data['page'] = 1;
		}
		if (!isset($data['num'])) {
			$data['num'] = 10;
		}
		# 2.查询数据
		$where['article_isdel'] = 0;
		$count = db('article')->where($where)->count();
		$page_num = ceil($count / $data['num']);
		$field = "article_id,article_title,article_ctime,u.user_nickname";
		$join = [['api_user u', 'u.user_id=a.article_uid']];
		$res = db('article')->alias('a')->field($field)->where($where)->join($join)->page($data['page'], $data['num'])->select();
		if ($res === false) {
			$this->return_msg(100002, '文章查询失败');
		} elseif (empty($res)) {
			$this->return_msg(200, '暂无数据');
		} else {
			$return_data['article_list'] = $res;
			$return_data['page_num'] = $page_num;
			$this->return_msg(200, '查询成功', $return_data);
		}

	}
	/**
	 * [article_detail 查看文章详情]
	 * @return [type] [返回结果]
	 */
	public function article_detail() {
		# 1.接受参数
		$data = $this->params;
		# 2.查询数据
		$where['article_id'] = $data['id'];
		$field = "article_id,article_title,article_content,article_ctime,u.user_nickname";
		$join = [['api_user u', 'u.user_id=a.article_uid']];
		$res = db('article')->alias('a')->field($field)->where($where)->join($join)->find();
		$res['article_content'] = htmlspecialchars_decode($res['article_content']);
		# 3.返回结果通知
		if (!$res) {
			$this->return_msg(100003, '查询失败');
		}
		$this->return_msg(200, '数据查询成功', $res);
	}
	/**
	 * [edit_article 修改文章]
	 * @return [json] [返回结果]
	 */
	public function edit_article() {
		#1.接收参数
		$data = $this->params;
		#2.修改数据
		$res = db('article')->where('article_id', $data['article_id'])->update($data);
		#3.结果返回通知
		if ($res === false) {
			$this->return_msg(100004, '修改失败');
		}
		$this->return_msg(200, '修改成功');
	}
	/**
	 * [delect_article 删除文章]
	 * @return [json] [返回结果]
	 */
	public function delect_article() {
		# 1.接受参数
		$data = $this->params;
		# 2.删除数据
		$res = db('article')->where($data)->setField('article_isdel', 1);
		# 3.结果返回通知
		if (!$res) {
			$this->return_msg(100005, '数据删除失败');
		}
		$this->return_msg(200, '数据删除成功');
	}
}